package common

import (
	"time"

	"github.com/dgrijalva/jwt-go"
)

//jwt的服务器密钥
var jwtkey = []byte("yaojingli")

type Claims struct {
	Account  string
	Username string
	Class    string
	jwt.StandardClaims
}

func ReleaseToken(account, username, class string) (string, error) {
	//tokend的过期时间为7天
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		Account:  account,
		Username: username,
		Class:    class,
		StandardClaims: jwt.StandardClaims{
			//token过期时间
			ExpiresAt: expirationTime.Unix(),
			//token发放时间
			IssuedAt: time.Now().Unix(),
			//谁发放的token
			Issuer: username,
			//发放的主题
			Subject: "user login",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtkey)

	if err != nil {
		return "", err
	}
	return tokenString, nil
}

//解析token的信息
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtkey, nil
	})
	return token, claims, err
}
